const Redis = require('ioredis');
const {Ajax} = require("./Ajax");
const logging = require("./log");
const config = require("../config");
const redis = new Redis({
        port: config().redis.port,
        host: config().redis.host,
        family: config().redis.family,
        password: config().redis.password,
        db: config().redis.db
    });

redis.on('connect', () => {
    console.log('Redis connected');
});

redis.on('error', (error) => {
    console.error('Redis connection error:', error);
});

const RedisUtil = (type, name, value, ex) => {
    return new Promise((resolve, reject) => {
        if (type === 'set') {
            redis.set(name, value, 'EX', ex)
                .then(() => {
                    resolve(Ajax(200, `键${name}写入成功!`, new Date(new Date()).toLocaleString('zh-CN', {
                        timeZone: "Asia/Shanghai"
                    })))
                    logging('info', `键${name}写入成功!`)
                })
                .catch(error => {
                    reject(Ajax(301, `存入键${name}失败!`, error))
                    logging('error', `存入键${name}失败 ${error}`)
                })
        } else if (type === 'get') {
            redis.get(name)
                .then(res => {
                    resolve(res)
                    logging('info', `读取键${name}成功`)
                })
                .catch(error => {
                    reject(error)
                    logging('error', `读取键${name}失败 ${error}`)
                });
        } else {
            reject('Unknown operation type');
        }
    });
};

module.exports = RedisUtil;